package com.sdd.ga.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * ClassName: TimeCountGlobaFilter
 * Description: 接口耗时统计
 * date: 2020/7/7
 *
 * @author xugaojun
 */
@Slf4j
@Component
public class TimeCountGlobaFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 开始时间
        Long startTime = System.currentTimeMillis();
        // filter 方法作用将 exchange 交给下一个过滤器处理
        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            // 结束时间
            Long endTime = System.currentTimeMillis();
            if (log.isInfoEnabled()) {
                log.info(exchange.getRequest().getURI().getPath() + " ->> {} ms", (endTime - startTime));
            }
        }));
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
